package cn.ss.exam2302.service.impl;

import cn.ss.exam2302.entity.*;
import cn.ss.exam2302.mapper.AnswerMapper;
import cn.ss.exam2302.mapper.SingleMapper;
import cn.ss.exam2302.mapper.YesnoMapper;
import cn.ss.exam2302.service.QuestionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private SingleMapper singleMapper;
    @Autowired
    private YesnoMapper yesnoMapper;
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public JsonResult query(Integer paId, Integer pos) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.eq("ans_usr_id", userId);
        answerQueryWrapper.eq("ans_pa_id", paId);
        answerQueryWrapper.eq("ans_pos", pos);
        Answer answer = answerMapper.selectOne(answerQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        QueryWrapper<Single> singleQueryWrapper = new QueryWrapper<>();
        singleQueryWrapper.eq("sin_pa_id", paId);
        singleQueryWrapper.eq("sin_pos", pos);
        Single single = singleMapper.selectOne(singleQueryWrapper);
        if (single != null) {
            data.put("type", "single");
            data.put("ques", single);
            data.put("sel", answer != null ? answer.getAnsSelect() : null);
            return new JsonResult(JsonResult.SUCCESS, null, data);
        }
        QueryWrapper<Yesno> yesnoQueryWrapper = new QueryWrapper<>();
        yesnoQueryWrapper.eq("yn_pa_id", paId);
        yesnoQueryWrapper.eq("yn_pos", pos);
        Yesno yesno = yesnoMapper.selectOne(yesnoQueryWrapper);
        if (yesno != null) {
            data.put("type", "yesno");
            data.put("ques", yesno);
            data.put("sel", answer != null ? answer.getAnsSelect() : null);
            return new JsonResult(JsonResult.SUCCESS, null, data);
        }
        return JsonResult.JSONRESULT_FAIL;
    }
}
